﻿import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15

//1.需要补充判定游戏成功的条件；游戏成功之后，弹出记录对话框；
//2.添加记录游戏时间记录   本地数据库的数据；

Item {
    //send the rows and cols to create the scene
    id:swipeMine
    required property int gridRows
    required property int gridCols
    required property int mines
    //save the pos of mines
    property var mineSet
    //标记右键标志旗帜的个数
    property alias flagLabelText:flagLabel.text
    property alias timerLabelText: timeLabel.text
    //使用右键标志为雷的数量
    property int markGrid:0
    onMarkGridChanged: {
        flagLabel.text=markGrid+"/"+mines;
    }
//    signal markGridChanged(markGrid)    值更改时，更新flagLabelText的值
    //标记游戏是否开始    和是否结束
    property bool gameStart: false
    property bool gameEnd: false
    property int secs: 0;


    anchors.fill: parent
    Rectangle{
        anchors.margins: 20
        width:calcWidth()-40
        height:width*0.8/gridCols*gridRows-40
        anchors.centerIn: parent
        //用于计算子窗口的宽度和高度   按照右侧按键栏  占左侧方块栏的1/4计算
        function calcWidth()
        {
            var width=swipeMine.width;
            var height=swipeMine.height;
            console.log("swipeMine width=",width);
            console.log("swipeMine height=",height);
            //×1000之后再进行整除操作，是为了防止结果为0
            var wRatio=1.2*gridCols*1000/width;
            var hRatio=gridRows*1000/height;
//            console.log("wRatio=",wRatio);
//            console.log("hRatio=",hRatio);
            var retWidth=0;
            var retHeight=0;
            //取占比比较大的一方
            if (wRatio<=hRatio){
                retHeight=parent.height;
                retWidth=retHeight/gridRows*gridCols*1.2;
                console.log("retWidth1=",retWidth);
                console.log("retHeight1=",retHeight);
            }
            else{

                retWidth=parent.width;
                retHeight=retWidth*0.83/gridCols*gridRows;
                console.log("retWidth2=",retWidth);
                console.log("retHeight2=",retHeight);
            }

            return retWidth;
        }
        Row{
            anchors.fill: parent
            ListModel{
                id:gridModel
            }
            GridView{
                id:gridView
                width:parent.width*0.83
                height:parent.height
                flow:GridView.FlowLeftToRight
                layoutDirection: Qt.LeftToRight
                verticalLayoutDirection: GridView.TopToBottom
                model:gridModel
                delegate: gridDelegate
                //带有间隙的网格的高度和宽度
                cellHeight: height/gridRows
                cellWidth: width/gridCols
            }
            Component{
                id:gridDelegate
                Rectangle{
                    id:gridRect
                    height:gridView.height/gridRows-5
                    width:gridView.width/gridCols-5
                    property int value: gridValue
                    property alias text: numText.text
                    property alias imageSource:gridImage.source
                    Text {
                        id:numText
                        anchors.centerIn: parent
                        font.pixelSize: parent.height/2
                        font.bold: true
                    }
                    Image{
                        id:gridImage
                        anchors.fill: parent
                        fillMode: Image.PreserveAspectFit
                    }
                    //将状态放在模型中进行标记
                    state: delegateState
                    //四种状态   未被翻开   被翻开   被右键标记   jieshu
                    states: [
                        State {
                            name: "originalState"
                            PropertyChanges {
                                target: gridRect
                                color:"#babdb6"
                            }
                        },
                        State{
                            name:"leftClickedState"
                            PropertyChanges {
                                target: gridRect
                                color:getGridColor(value)
                                //显示表格的值
                                text:value
                            }
                        },
                        State{
                            name:"rightClickedState"
                            PropertyChanges {
                                target: gridRect
                                color:"#babdb6"
                                imageSource: "qrc:/assets/slogan.png"
                            }
                        },
                        State{
                            name:"clickedMine"
                            PropertyChanges {
                                target: gridRect
                                color:"#babdb6"
                                imageSource:"qrc:/assets/mine_red.png"
                            }
                        },
                        State{
                            name:"otherMine"
                            PropertyChanges {
                                target: gridRect
                                color:"#babdb6"
                                imageSource:"qrc:/assets/mine_black.png"
                            }
                        }
                    ]
                    //通过鼠标点击实现不同状态的切换
                    MouseArea{
                        id:clickGridMouseArea
                        anchors.fill: parent
                        acceptedButtons: Qt.LeftButton|Qt.RightButton
                        enabled: clickEnabled
                        onClicked: {
                            console.log("value=",value);
                            if (mouse.button===Qt.LeftButton){
                                //需要增加点击逻辑
                                if (delegateState==="originalState"){
                                    onLeftClicked(index);
                                    if (gameStart===false){
                                        gameStart=true;
                                        timer.start();
                                    }
                                    // gridModel.append({"index":i,"gridValue":0,"delegateState":"originalState"})
                                }
                                else{
                                    return;
                                }
                            }
                            else if (mouse.button===Qt.RightButton){
//                                console.log("right button has clicked!");
                                if (delegateState==="originalState"){
                                    delegateState="rightClickedState";
                                    markGrid+=1;
//                                    markGridChanged();
                                }
                                else if (delegateState==="rightClickedState"){
                                    delegateState="originalState";
                                    markGrid-=1;
//                                    markGridChanged();
                                }
                                else{
                                    return;
                                }
                            }
                        }
                    }
                    //根据值的不同，对左键点击做出不同的反应
                    function onLeftClicked(centerIndex)
                    {
                        if (gridModel.get(centerIndex).delegateState!=="originalState"){
                            return;
                        }
                        if (gridModel.get(centerIndex).gridValue>0){
                            gridModel.get(centerIndex).delegateState="leftClickedState";
                            return;
                        }
                        //代表左键点击的是雷   应该结束游戏
                        else if (gridModel.get(centerIndex).gridValue<0){
                            gridModel.get(centerIndex).delegateState="clickedMine";
                            timer.stop();
                            mineSet.forEach(function(value, index, array){
                                if (centerIndex===value){

                                }
                                else{
                                    gridModel.get(value).delegateState="otherMine";
                                }
                            })
                            let total=gridRows*gridCols;
                            for(let i=0;i<total;i++){
                                gridModel.get(i).clickEnabled=false;
                            }
                            return;
                        }
                        else {
                            gridModel.get(centerIndex).delegateState="leftClickedState";
                            let aroundIndex=getAroundIndex(centerIndex);

                            let length=aroundIndex.length;
                            //周边不是雷区的区域   递归处理
                            for(let j=0;j<length;j++){
                                console.log("aroundIndex["+j+"]="+aroundIndex[j]);
                                //加第二个判断条件，防止无限递归
                                if (gridModel.get(aroundIndex[j]).gridValue!==-1&& gridModel.get(aroundIndex[j].delegateState==="originalState")){
                                    onLeftClicked(aroundIndex[j]);
                                }
                            }
                        }

                    }
                    //根据值的不同生成不同的颜色
                    function getGridColor(value)
                    {
                        switch(value){
                        case -1:
                            return "#dededc"
                            case 0:
                            return "#dededc";
                            case 1:
                            return "#7FFFD4";
                            case 2:
                            return "#F5DEB3";
                            case 3:
                            return "#EEC591";
                            case 4:
                            return "#EEAD0E";
                            case 5:
                            return "#FF8247";
                            case 6:
                            return "#FF7256";
                            case 7:
                            return "#FF6347";
                            case 8:
                            return "#FF34B3";
                        }
                    }
                    function getText(value)
                    {
                        if (value>=1&&value<=8){
                            return value;
                        }
                        return null;
                    }
                }
            }
            ColumnLayout{
                width:parent.width*0.17
                height:parent.height
                Image {
                    id: flagImage
                    source: "qrc:/assets/flag.png"
                    Layout.preferredWidth: 40;Layout.preferredHeight: 40
                    Layout.alignment: Qt.AlignHCenter
                    fillMode: Image.PreserveAspectFit
                }
                Label{
                    id:flagLabel
                    Layout.alignment: Qt.AlignHCenter
                    text:"0/"+mines
                    minimumPixelSize: 20
                }
                Image{
                    id:timerImage
                    source: "qrc:/assets/timer.png"
                    width:40;height:40
                    Layout.preferredWidth: 40;Layout.preferredHeight: 40
                    Layout.alignment: Qt.AlignHCenter
                    fillMode: Image.PreserveAspectFit
                }
                Label{
                    id:timeLabel
                    Layout.alignment: Qt.AlignHCenter
                    minimumPixelSize: 20
                    text: "00:00"
                }
                Item{
                    Layout.fillHeight: true
                    Layout.fillWidth: true
                }
                Button{
                    id:reSelect
                    height:40
                    Layout.fillWidth: true
                    Layout.alignment: Qt.AlignHCenter
                    Layout.leftMargin: 10
                    Layout.rightMargin: 10
                    text: qsTr("选择难度")
                    onClicked: {
                        stackView.pop()
                    }
                }
                Button{
                    id:reStart
                    height:40
                    Layout.fillWidth: true
                    Layout.alignment: Qt.AlignHCenter
                    Layout.leftMargin: 10
                    Layout.rightMargin: 10
                    text: qsTr("重新开始")
                    onClicked:{
                        //重置游戏时间
                        timerLabelText="00:00";
                        timer.restart();
                        //重置旗帜
                        markGrid=0;
                        //重新生成游戏数据，并将所有状态设置为未点击状态；   未设置完毕！！！
                        generateGrid();
                        var total=gridCols*gridRows;
                        for(var i=0;i<total;i++){
                            gridModel.get(i).delegateState="originalState";
                        }
                    }
                }
                Button{
                    id:pauseBtn
                    height:40
                    state: "resume"
                    states:[
                        State {
                            name: "pause"
                            PropertyChanges {
                                target: pauseBtn
                            }
                        },
                        State{
                            name:"resume"
                            PropertyChanges {
                                target: pauseBtn
                            }
                        }
                    ]
                    Layout.fillWidth: true
                    Layout.alignment: Qt.AlignHCenter
                    Layout.leftMargin: 10
                    Layout.rightMargin: 10
                    text:qsTr("暂停")
                    onClicked:{
                        if (pauseBtn.state==="pause"){
                            pauseBtn.state="resume";
                            pauseBtn.text=qsTr("继续");
                            timer.stop();
                        }
                        else{
                            pauseBtn.state="pause";
                            pauseBtn.text=qsTr("暂停");
                            timer.start();
                        }
                    }
                }
            }
            Timer{
                id:timer
                interval: 1000
                repeat: true
                onTriggered: {
                    secs+=1;
                    var minutes=Math.floor(secs/60);
                    if (minutes.toString().length==1){
                        minutes="0"+minutes;
                    }
                    var seconds=secs%60;
                    if (seconds.toString().length==1){
                        seconds="0"+seconds;
                    }
                    var str=minutes+":"+seconds;
                    timeLabel.text=str;
                }
            }
        }

    }
    Component.onCompleted: {
        generateGrid();
    }
    //生成所有的雷区数据
    function generateGrid()
    {
        var total=gridRows*gridCols;
        //js中的set对象
        mineSet=new Set();
        while(mineSet.size<mines){
            //生成0~total之间的随机数
            var index=Math.floor(Math.random()*total);
            console.log("index=",index);
            mineSet.add(index);
        }
        gridModel.clear();
        for(let i=0;i<total;i++){
            if (mineSet.has(i)){
                console.log("i in mineSet, i=",i);
                gridModel.append({"index":i,"gridValue":-1,"delegateState":"originalState","clickEnabled":true});
                continue;
            }
            gridModel.append({"index":i,"gridValue":0,"delegateState":"originalState","clickEnabled":true});
            //测试用句，用于检测生成的网格是否符合逻辑
//            gridModel.append({"index":i,"gridValue":0,"delegateState":"leftClickedState"});
        }
        for (let i=0;i<total;i++){
            let value=gridModel.get(i).gridValue;
            if (value===-1) continue;
            else{
                value=0;
                var aroundIndex=getAroundIndex(i)
                var length=aroundIndex.length;
                for(let j=0;j<length;j++){
                    if (gridModel.get(aroundIndex[j]).gridValue===-1){
                        value++;
                    }
                }
                if (value===0){
                    console.log(i+".gridValue=0");
                }
                gridModel.get(i).gridValue=value;
            }
        }
    }
    //get the effective index around centerIndex
    function getAroundIndex(centerIndex)
    {
        var xPos=centerIndex%gridCols;
        var yPos=Math.floor(centerIndex/gridCols);
        var aroundIndex=[];
        var retAroundIndex=[];
        aroundIndex[0]={"x":xPos-1,"y":yPos-1};
        aroundIndex[1]={"x":xPos,"y":yPos-1};
        aroundIndex[2]={"x":xPos+1,"y":yPos-1};
        aroundIndex[3]={"x":xPos-1,"y":yPos};
        aroundIndex[4]={"x":xPos+1,"y":yPos};
        aroundIndex[5]={"x":xPos-1,"y":yPos+1};
        aroundIndex[6]={"x":xPos,"y":yPos+1};
        aroundIndex[7]={"x":xPos+1,"y":yPos+1};
        for(let j=0;j<8;j++){
            var curIndex=aroundIndex[j].y*gridCols+aroundIndex[j].x;
            if (aroundIndex[j].x>=0&& aroundIndex[j].x<gridCols&&aroundIndex[j].y>=0&& aroundIndex[j].y<gridRows){
                retAroundIndex.push(curIndex);
            }
        }
        return retAroundIndex;
    }
}
